package org.cliff.message.platform.config;

import org.cliff.message.platform.core.response.CommonResponseBuilder;
import org.cliff.message.platform.core.service.DisposableWorkerIdAssigner;
import org.cliff.message.platform.ext.lock.RedissonDistributeLockImpl;
import com.xfvape.uid.impl.DefaultUidGenerator;
import org.mybatis.spring.annotation.MapperScan;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * 消息平台自动配置类
 * 集成系统可以通过声明 {@link org.springframework.context.annotation.Primary} 的方式来替换此处加载的bean实现
 *
 * @author 刘文
 * @date 2023/10/9
 */
@MapperScan("org.cliff.message.platform.core.mapper")
@ComponentScan("org.cliff.message.platform")
@EnableScheduling
public class MessagePlatformAutoConfiguration {

    @Bean
    public DefaultUidGenerator defaultUidGenerator(DisposableWorkerIdAssigner disposableWorkerIdAssigner) {
        DefaultUidGenerator defaultUidGenerator = new DefaultUidGenerator();
        defaultUidGenerator.setWorkerIdAssigner(disposableWorkerIdAssigner);

        defaultUidGenerator.setEpochStr("2023-09-20");
        // 支持200年
        defaultUidGenerator.setTimeBits(34);
        defaultUidGenerator.setWorkerBits(16);
        // 支持8k/s
        defaultUidGenerator.setSeqBits(13);
        return defaultUidGenerator;
    }

    /**
     * 通用响应生成器，集成系统可以通过 {@link org.springframework.context.annotation.Primary}
     * 的方式来注入扩展的CommonResponseBuilder,生成自己系统的统一Response
     *
     * @return
     */
    @Bean
    public CommonResponseBuilder commonResponseBuilder() {
        return new CommonResponseBuilder();
    }

    /**
     * Redisson分布式锁实现简单集成，业务系统也可以定义自己的分布式锁
     * @param redissonClient
     * @return
     */
    @Bean
    @ConditionalOnClass(RedissonClient.class)
    public RedissonDistributeLockImpl redissonDistributeLock(RedissonClient redissonClient) {
        RedissonDistributeLockImpl redissonDistributeLock = new RedissonDistributeLockImpl(redissonClient);
        return redissonDistributeLock;
    }
}
